import StandProductList from '@/components/product/StandProductList';
import StandProductSort, { SortFilter } from '@/components/product/StandProductSort';
import SearchRedirect from '@/components/StandSearch/Redirect';
import { customeAppId } from '@/src/config';
import utils from '@/utils';
import { useShowLoading } from '@/utils/hooks/useShowLoading';
import { View } from '@tarojs/components';
import Taro, { useRouter } from '@tarojs/taro';
import React, { useCallback, useEffect, useState } from 'react';
import { connect } from 'react-redux';
import { parseParams } from './helper';
import './index.scss';

const AppProducts = ({ loading, dispatch, appProductList, appProductListFinished }) => {
  const isLoading = useShowLoading(loading, ['productList/fetchAppProductList']);

  const { params: { goodsSelectInfo, title = '更多商品' } = {} } = useRouter();
  const baseParams = parseParams(goodsSelectInfo);

  const keywords = baseParams?.name ?? '';
  const [sort, setSort] = useState(baseParams?.sort ?? SortFilter.comprehensive);

  const getNextList = useCallback(
    (params) => {
      return dispatch({
        type: 'productList/fetchAppProductList',
        payload: {
          type: 4,

          ...baseParams,

          pageSize: 10,

          name: keywords,
          sort,
          appid: customeAppId,

          ...params,
        },
      });
    },
    [keywords, sort],
  );

  useEffect(() => {
    getNextList({ page: 1 });
  }, [keywords, sort]);

  useEffect(() => {
    utils.setTitle(decodeURIComponent(title));
  }, [title]);

  return (
    <View className="AppProducts">
      <View className="search-container">
        <SearchRedirect
          placeholder={keywords}
          onClick={() => {
            Taro.navigateTo({
              url:
                '/mainSubPack/appProducts/appProductsSearch/index?goodsSelectInfo=' +
                goodsSelectInfo,
            });
          }}
        />
      </View>

      <StandProductSort
        {...{
          value: sort,
          onChange: setSort,
        }}
      />

      <StandProductList
        {...{
          className: 'product-list',
          height: utils.getCalcHeight({}, 200, 30),
          list: appProductList,
          finished: appProductListFinished,
          isLoading,

          onNext: getNextList,
        }}
      />
    </View>
  );
};
export default connect(({ loading, productList }) => ({
  loading,

  appProductList: productList.appProductList,
  appProductListFinished: productList.appProductListFinished,
}))(AppProducts);
